/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.orderscanner.impl;

import com.lightkits.common.db.entity.WmExecuteLine;
import com.lightkits.common.db.entity.WmSaleTicketLine;
import com.lightkits.common.db.entity.WmSalesTicket;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.deliveryorder.service.CreateDeliveryOrderDomain;
import com.lightkits.wms.domain.orderscanner.CreateDocScanParams;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.dto.orderscanner.model.ScannerHeaderDto;
import com.lightkits.wms.dto.orderscanner.model.ScannerLineDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author jing.wei@hand-china.com
 * @date 2019/6/20 16:50
 **/
@Service
public class CreateDocScanParamsImpl implements CreateDocScanParams {
    private final Logger logger = LoggerFactory.getLogger(CreateDocScanParamsImpl.class);

  @Autowired
  private DocumentServiceClient client;

    /**
     * 售货单头的创建
     *
     * @param headDto
     * @return
     **/
    @Override
    public CheckResult<WmSalesTicket> createSaleHead(ScannerHeaderDto headDto) {
        CheckResult<WmSalesTicket> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
            WmSalesTicket salesTicket = new WmSalesTicket();
            GenerateDocNumRequestType request = new GenerateDocNumRequestType();
            request.setCount(1);
            request.setSize(4);
            request.setType("ST");
            request.setField1(df.format(new Date()));
            GenerateDocNumResponseType response = client.generateDocNumber(request);
            salesTicket.setSalesTickeetNum(response.getDocNumList().get(0));
            salesTicket.setOrganizationId(ParseUtil.tryLongWithException(headDto.getOrgId()));
            if (!ObjectUtil.isNullOrEmpty(headDto.getWorkerId())) {
                salesTicket.setWorkerId(ParseUtil.tryLongWithException(headDto.getWorkerId()));
            }
            if (!ObjectUtil.isNullOrEmpty(headDto.getPriceTotal())) {
                salesTicket.setPriceTotal(new BigDecimal(headDto.getPriceTotal()));
            }
            if (!ObjectUtil.isNullOrEmpty(headDto.getFreight())) {
                salesTicket.setFreight(new BigDecimal(headDto.getFreight()));
            }
            salesTicket.setCurrency(headDto.getCurrency());
            salesTicket.setDeliverWays(headDto.getDelieveyWays());
            salesTicket.setGoodsTotal(new BigDecimal(headDto.getGoodTotal()));
            salesTicket.setInvoice(headDto.getInvoice());
            salesTicket.setBookedMoney(new BigDecimal(headDto.getBookMoney()));
            salesTicket.setCustomerAddress(headDto.getCustomerAddress());
            salesTicket.setCustomerName(headDto.getCustomerName());
            salesTicket.setDeliverAddress(headDto.getCustomerAddress());
            salesTicket.setCustomerPhone(headDto.getCustomerPhone());
            salesTicket.setSoStatus(headDto.getSoStatus());
            checkResult.setData(salesTicket);

        } catch (Exception e) {
            logger.error("createSaleHead.error", e);
        }
        return checkResult;
    }

    /**
     * 创建售货单行
     *
     * @param lineDtos 售货单行参数
     * @param headId   售货单头ID
     * @param currency 货币
     * @return WmSaleTicketLine
     **/
    @Override
    public CheckResult<List<WmSaleTicketLine>> createSaleLine(List<ScannerLineDto> lineDtos,
                                                              Long headId, String currency) {
        CheckResult<List<WmSaleTicketLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        try {
            List<WmSaleTicketLine> lines = new ArrayList<>();
            lineDtos.forEach(line -> {
                WmSaleTicketLine saleTicketLine = new WmSaleTicketLine();
                saleTicketLine.setCurrency(currency);
                saleTicketLine.setItemId(ParseUtil.tryLongWithException(line.getItemId()));
                saleTicketLine.setSalesTicketId(headId);
                saleTicketLine.setTagId(ParseUtil.tryLongWithException(line.getTagId()));
                lines.add(saleTicketLine);
            });
            checkResult.setData(lines);
        } catch (Exception e) {
            logger.error("createSaleLine.error", e);
            throw new LightKitsBizException(e);
        }
        return checkResult;
    }

    /**
     * 创建售货单行
     *
     * @param lineDtos 售货单行参数
     * @return
     **/
    @Override
    public CheckResult<List<WmExecuteLine>> createExeLine(List<ScannerLineDto> lineDtos,
                                                          List<WmSaleTicketLine> saleTicketLines,
                                                          Long headerId,
                                                          Long eventId) {
        CheckResult<List<WmExecuteLine>> checkResult = new CheckResult<>();
        checkResult.setSuccessful(true);
        try {
            List<WmExecuteLine> lines = new ArrayList<>();
            lineDtos.forEach(line -> {
                WmExecuteLine executeLine = new WmExecuteLine();
                executeLine.setDocumentType("SALETICKET");
                executeLine.setExecuteType("挑库");
                executeLine.setItemId(ParseUtil.tryLongWithException(line.getItemId()));
                executeLine.setUom(line.getUomCode());
                executeLine.setExecutedTime(new Date());
                executeLine.setEventId(eventId);
                executeLine.setDocumentId(headerId);
                Optional<WmSaleTicketLine> opt = saleTicketLines.stream().filter(target -> target.getTagId().toString()
                        .equals(line.getTagId())).findFirst();
                executeLine.setDocumentLineId(opt.get().getId());
                executeLine.setTagId(ParseUtil.tryLongWithException(line.getTagId()));
                executeLine.setTagCode(line.getTagCode());
                executeLine.setWarehouseId(ParseUtil.tryLongWithException(line.getWarehouseId()));
                executeLine.setLotNumber(line.getLotNum());
                executeLine.setExecutedQty(new BigDecimal(line.getQuantity()));
                if (!ObjectUtil.isNullOrEmpty(line.getWmAreaId())) {
                    executeLine.setWmAreaId(ParseUtil.tryLongWithException(line.getWmAreaId()));
                }
                if (!ObjectUtil.isNullOrEmpty(line.getLocationId())) {
                    executeLine.setLocationId(ParseUtil.tryLongWithException(line.getLocationId()));
                }
                lines.add(executeLine);
            });
            checkResult.setData(lines);
        } catch (Exception e) {
            logger.error("create Execute Line.error", e);
        }
        return checkResult;
    }
}
